/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var actionForm = 'mappingAction.php';
var popAutoFilter = "autoFilterMappingPop.php";
var popGlosario = "glosarioPop.php";
var popAutoFilterPOIs = "autoFilterPOIsPop.php";
var popAutoFilterEVPs = "autoFilterEVPsPop.php";
var popCampannas = "mappingCampannaPop.php";
var popUploadExcel = "mappingExcelPop.php";
var popCampannasItem = "mappingCampannaItemPop.php";

//Variables de Filtro Mapping
var joElementosMap = undefined;
var joEVPMap = undefined;
var joProvinciaMap = undefined;
var joLocalidadMap = undefined;
var joEntidadPoisMap = undefined;
var joFavoritosMap = undefined;
var joUbicacionesCantidad = [];
var joMarkerNotVisibleIds = [];
var joImagenesMapa;
var bPopLoaded = false;

var jaDataPolygon = [
                     	{circlePois: false, mtsRadio: 0},
                     	{circleElementos: false, mtsRadio: 0},
                     	{circleEVPs: false, mtsRadio: 0}
                     ];

var joFilterUbicaciones = undefined;
var oTableMAP;
var oTableCampannas;
var joDataCampanna;
var emptyTable = true;
var bolPrintMarca = false;

var actionPKCampanna = undefined;
var action = undefined;

var iFilterMapping = new fn_colFilterMapping();

function fn_colFilterMapping()
{
	this.ELEMENTO = 0;
	this.EVP = 1;
	this.PROVINCIA = 2;
	this.LOCALIDAD = 3;
	this.POIS = 4;
}

function $_init()
{
	joFavoritosMap = [];
	joUbicacionesCantidad = [];
	
	joFilterUbicaciones = {
							joElementosIds : joElementosMap, 
							joEVPIds: joEVPMap, 
							joProvinciaIds : joProvinciaMap, 
							joLocalidadIds: joLocalidadMap,
							joEntidadPOIs: joEntidadPoisMap,
							joFavoritosIds: joFavoritosMap
						};
	
	$('.btnNav').each(function (i){
		$(this).removeClass($(this).attr('id')+'Act');
		$(this).addClass($(this).attr('id'));
	});
	$('#btnMapp').addClass('btnMappAct');
	
	$('#mapping').goMap({
		address: 'Argentina',
		zoom: 5,
		streetViewControl: true,
		maptype: 'ROADMAP',
		addMarker: libPoly
	});
	
	$('#titleCampanna').dblclick(function() {
		actionPKCampanna = undefined;
		$_limpiarFiltrosCampanna();
		$(this).hide();
	});
	
	$('#btnGrabarMapa').click(function() {
		html2canvas($(".gm-style"), {
			useCORS: true,
            onrendered: function(canvas) {
                theCanvas = canvas;
                canvas.toBlob(function(blob) {
                    saveAs(blob, "Mapa.png"); 
                });
            }
        });

	});
	
	$('#btnGlosario').click(function() {
		$('#glosarioDialog').load(popGlosario).dialog('open');
	});
	
	$('#btnExportExcel').click( function(e) {
		var paramData = 'actionOfForm=exportXLS&joFilterUbicaciones=' + encodeURIComponent(JSON.stringify(joFilterUbicaciones)) + '&joMarkerVisibleIds=' +  encodeURIComponent($.goMap.getMarkers('Ids'));
		
		if(!$.browser.msie)
			location.href = actionForm + '?' + paramData;
		else
			window.open(actionForm + '?' + paramData);
	});
	
	$('#btnRefreshGrid').click( function(e) {
		//Oculto los No Favoritos
		oTableMAP.$('tr').each(function() {
		    var aData = oTableMAP.fnGetData(this);
		    var idFavorito = $(aData[12]).attr('id');
		    var oFavorito = $('#'+idFavorito).attr('src');
		    var idMarker = $('#'+idFavorito).attr('id').split("_")[2];
		    
		    if(oFavorito.indexOf('desactivado') != -1) {
		    	$_setVisibleMarker(idMarker, false)
		    	joMarkerNotVisibleIds.push(idMarker);
		    }
		});
		
		oTableMAP.fnReloadAjax(actionForm + "?actionOfForm=searchMapping");
		bolPrintMarca = true;
	});
	
	$('#btnFavoritosGrid').click( function(e) {
		if($(this).hasClass('desactivado')) {
			oTableMAP.$('tr').each(function() {
			    var aData = oTableMAP.fnGetData(this);
			    var idFavorito = $(aData[12]).attr('id');
			    var oFavorito = $('#'+idFavorito).attr('src');
			    var idMarker = $('#'+idFavorito).attr('id').split("_")[2];
			    
			    if(oFavorito.indexOf('desactivado') != -1) {
			    	$_setVisibleMarker(idMarker, false)
			    	$(this).hide();
			    }
			});
			$(this).removeClass('desactivado');
			$(this).addClass('activado');
		}
		else {
			oTableMAP.$('tr').each(function() {
				var aData = oTableMAP.fnGetData(this);
			    var idFavorito = $(aData[12]).attr('id');
			    var oFavorito = $('#'+idFavorito).attr('src');
			    var idMarker = $('#'+idFavorito).attr('id').split("_")[2];
			    
				$_setVisibleMarker(idMarker, true)
				$(this).show();
			});
			$(this).removeClass('activado');
			$(this).addClass('desactivado');
		}
	});
	
	$('#btnCampanna').click(function(){
		$('#mappingCampannaDialog').load(popCampannas).dialog('open');
	});
	
	$('#btnUploadExcel').click(function(){
		$('#mappingExcelDialog').load(popUploadExcel).dialog('open');
	});
		
	$('#btnGrabarFiltro').click( function(e) {
		$_grabarFiltro();
	});
	
	$('#btnActulizarMapa').click( function(e) {
		joMarkerNotVisibleIds = [];
		$_actulizarMapa();
		
		//Guardo la Campanna si esta seleccionada
		$_saveFilterCampanna();
	});
		
	$('#btnMostrarFiltros').click( function(e) {
		$('#mappingVerFiltros').load('mappingVerFiltrosPop.php?joFilterUbicaciones=' + encodeURIComponent(JSON.stringify(joFilterUbicaciones))).dialog('open');
	});
	
	$('#btnMaxMin').click( function(e) {
		if($(this).attr('class') == 'btnMaximizarGrid'){
			$('#tablaReferencias').css({top : '220px', height: '640px'});
			$('div.dataTables_scrollBody').height('520px');
			$(this).attr("class", "btnMinimizarGrid"); 
		}
		else {
			$('#tablaReferencias').css({top : '620px', height: '240px'});
			$('div.dataTables_scrollBody').height('120px');
			$(this).attr("class", "btnMaximizarGrid");
		}
	});
	
	$('#btnVerGrilla').click( function(e) {
		if($(this).parent().attr('class') == "showTable") {
			$(this).parent().removeClass('showTable');
			$(this).parent().addClass('hideTable');
			$('#tablaReferencias').show("slide", { direction: "left" }, 1000);
		} 
		else {
			$(this).parent().removeClass('hideTable');
			$(this).parent().addClass('showTable');
			$('#tablaReferencias').hide("slide", { direction: "left" }, 1000);
		}
	});
	
	oTableMAP = $('#dt_referencias').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bAutoWidth": true,
			        "sScrollY" : "120px",
			        "bScrollInfinite": true,
			        "bScrollCollapse" : false,
					"bLengthChange": false,
					"bProcessing": true,
					"bServerSide": true,
					"iDisplayLength": -1,
					"oLanguage": {
						"sUrl": "js/datatables/js/dataTables.es.txt"
					},
					"sAjaxSource": actionForm + "?actionOfForm=searchMapping&emptyTable=true",
					"fnServerParams": function ( aoData ) {
						aoData.push( 
										{"name": "tipoFiltro", "value": $('#tipoFiltro').val()},
										{"name": "joFilterUbicaciones", "value": JSON.stringify(joFilterUbicaciones)}
									);
					},
					"fnDrawCallback": function(oSettings, json) {
						oTableMAP.$('tr').each(function() {
						    var aData = oTableMAP.fnGetData(this);
						    var aPos = oTableMAP.fnGetPosition(this);
						    var idUbicacion = ($(aData[12]).attr('id')).replace('fav_grilla_', '');
						    
						    if($.inArray(idUbicacion, joMarkerNotVisibleIds) > -1)
						    	$(this).hide();
						    
						});
					},
					"aoColumnDefs": [{
						"aTargets": [0],
						"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
								var valRef = oData[0].split("|");
								$.each(joImagenesMapa, function(i, val){
									if(val.id == valRef[0]) {
										sHtml = "<img src='"+val.imagen+"' onclick='$_centerMapMarker("+valRef[1]+", "+valRef[2]+")' />";
										$(nTd).html(sHtml);
										return false;
									}
								});
			  	      		}
						}],
					"aoColumns": [
					  			{"sClass" : "center"},
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			{ "sWidth": "7%", "sClass": "center", "bSortable": false } //Favorito
					  		]
			
				});
	
	$('.dataTables_scrollBody').css('background-color', '#E2E4FF');
	
	emptyTable = false;

	createUploader();
		
	//Eventos de Autofiltro	
	$('#btnElemento').click( function(e) {
		$_autofilterProxyShowMapping(iFilterMapping.ELEMENTO);
	});
	$('#btnEVP').click( function(e) {
		$_autofilterProxyShowMapping(iFilterMapping.EVP);
	});
	$('#btnProvincia').click( function(e) {
		$_autofilterProxyShowMapping(iFilterMapping.PROVINCIA);
	});
	$('#btnLocalidad').click( function(e) {
		$_autofilterProxyShowMapping(iFilterMapping.LOCALIDAD);
	});
	$('#btnPOIs').click( function(e) {
		$_autofilterProxyShowMapping(iFilterMapping.POIS);
	});
	
	$_initAutofilterDialog();
	
	$("#mappingExcelDialog").dialog({
		autoOpen:false, 
		height:'auto',  
		width:400, 
		modal: true,
		closeOnEscape: false,
		position : ['center',10],
		dialogClass:'no-close',
		open: function() {
			$('#mappingExcelDialog').css('background','#F5F5F5');
		}
	});
	
	$("#mappingCampannaDialog").dialog({
		autoOpen:false, 
		height:'auto',  
		width:760, 
		modal: true,
		closeOnEscape: false,
		position : ['center',10],
		dialogClass:'no-close',
		close: function(){
			oTableCampannas = undefined;
		},
		open: function() {
			$('#mappingCampannaDialog').css('background','#F5F5F5');
		}
	});
	
	$("#mappingFotosDialog").dialog({
		autoOpen:false, 
		height:'auto',  
		width:760, 
		modal: true,
		closeOnEscape: false,
		position : ['center',10],
		dialogClass:'no-close',
		open: function() {
			$('#mappingFotosDialog').css('background','#F5F5F5');
		}
	});
	
	$("#mappingVerFiltros").dialog({
		autoOpen:false, 
		height:'auto', 
		width:350, 
		modal: true,
		resizable: false,
		closeOnEscape: false,
		position : ['center',10],
		dialogClass:'no-close',
		open: function() {
			$('#mappingVerFiltros').css('background','#F5F5F5');
		}
	});
	
	$("#glosarioDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:550, 
		modal: true,
		resizable: false,
		closeOnEscape: false,
		position : ['center',10],
		dialogClass:'no-close',
		open: function() {
			$('#glosarioDialog').css('background','#F5F5F5');
		}
	});
}

function $_initVerFiltros()
{
	$("#Filtros").treeview();
	$('#btnVerFiltrosSalir').click( function(e) {
		$('#mappingVerFiltros').dialog('close');
	});
	
	$('#btnLimpiarFiltros').click( function(e) {
		$("#cleanFilterDialog").dialog({
			autoOpen: false, 
			height:'auto',
			width:350,
			position : ['center',10],
			open: function () {
				$('#cleanFilterDialog').css('background','#F5F5F5');
				$('#btnConfirmCleanFiltro').click( function(e) {
					joElementosMap = undefined;
					joEVPMap = undefined;
					joProvinciaMap = undefined;
					joLocalidadMap = undefined;
					joEntidadPoisMap = undefined;
					joFavoritosMap = [];
					joMarkerNotVisibleIds = [];
					joUbicacionesCantidad = [];
					
					var jaDataPolygon = [
					                     	{circlePois: false, mtsRadio: 0},
					                     	{circleElementos: false, mtsRadio: 0},
					                     	{circleEVPs: false, mtsRadio: 0}
					                     ];
					
					joFilterUbicaciones = {
							joElementosIds : undefined, 
							joEVPIds: undefined, 
							joProvinciaIds : undefined, 
							joLocalidadIds: undefined,
							joEntidadPOIs: undefined,
							joFavotirosIds: []
						};
					
					$.goMap.clearMarkers();

					oTableMAP.fnReloadAjax(actionForm + "?actionOfForm=searchMapping&emptyTable=true");
					bolPrintMarca = false;
					
					$('#cleanFilterDialog').dialog('close');
					$('#mappingVerFiltros').dialog('close');
				});
				$('#btnExitCleanFiltro').click( function(e) {
					$('#cleanFilterDialog').dialog('close');
				})
			}
		});
		$('#cleanFilterDialog').dialog('open');
	});
}

function $_imagenMappingProxyShow(idUbicacion) {
	$('#mappingFotosDialog').load('mappingFotos.php?idUbicacion=' + idUbicacion).dialog('open');
}

function $_autofilterProxyShowMapping(filter)
{
	joDataRowEnabled = [];
	joDataWhereFilter = [];
	
	//Define filters parameters
	switch (filter) {
		
		case iFilterMapping.ELEMENTO:
			tableFilter = "map_elementos";
			fieldsFilter = "descripcion";
			idTable = "idElemento";
			joDataFilter = joElementosMap;
			actualFilter = iFilterMapping.ELEMENTO;
			break;
			
		case iFilterMapping.EVP:
			tableFilter = "map_empresas";
			fieldsFilter = "descripcion";
			idTable = "idEmpresa";
			joDataFilter = joEVPMap;
			actualFilter = iFilterMapping.EVP;
			$('#autoFilterDialog').load(popAutoFilterEVPs).dialog('open');
			return;
			
		case iFilterMapping.PROVINCIA:
			tableFilter = "map_provincias";
			fieldsFilter = "descripcion";
			idTable = "idProvincia";
			joDataFilter = joProvinciaMap;
			actualFilter = iFilterMapping.PROVINCIA;
			break;
		
		case iFilterMapping.LOCALIDAD:
			tableFilter = "map_localidades";
			fieldsFilter = "descripcion";
			idTable = "idLocalidad";
			joDataFilter = joLocalidadMap;
			actualFilter = iFilterMapping.LOCALIDAD;
			joDataWhereFilter = {fieldFilter : 'idProvincia', dataWhereFilter : joProvinciaMap};
			break;
			
		case iFilterMapping.POIS:
			actualFilter = iFilterMapping.POIS;
			joDataFilter = joEntidadPoisMap;
			$('#autoFilterDialog').load(popAutoFilterPOIs).dialog('open');
			return;
	}
	
	$('#autoFilterDialog').load(popAutoFilter).dialog('open');
}

function $_initAutofilterDialog()
{
	$("#autoFilterDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:514,
		position : ['center',10],
		closeOnEscape: false,
		dialogClass:'no-close',
		beforeClose: function( event, ui ) {
			switch (actualFilter) {
				case iFilterMapping.ELEMENTO:
					joElementosMap = joDataFilter;
					joFilterUbicaciones.joElementosIds = joDataFilter;
					break;
				case iFilterMapping.EVP:
					joEVPMap = joDataFilter;
					joFilterUbicaciones.joEVPIds = joDataFilter;
					break;
				case iFilterMapping.PROVINCIA:
					joProvinciaMap = joDataFilter;
					joFilterUbicaciones.joProvinciaIds = joDataFilter;
					break;
				case iFilterMapping.LOCALIDAD:
					joLocalidadMap = joDataFilter;
					joFilterUbicaciones.joLocalidadIds = joDataFilter;
					break;
				case iFilterMapping.POIS:
					joEntidadPoisMap = joDataFilter;
					joFilterUbicaciones.joEntidadPOIs = joDataFilter;
					break;
			}
		},
		open: function() {
			$('#autoFilterDialog').css('background','#F5F5F5');
		}
	});
}

function $_grabarFiltro()
{
	var paramData = 'actionOfForm=grabarFiltro&joFilterUbicaciones=' + encodeURIComponent(JSON.stringify(joFilterUbicaciones))  + '&joMarkerNotVisibleIds=' +  encodeURIComponent(JSON.stringify(joMarkerNotVisibleIds));

	if(!$.browser.msie)
		location.href = actionForm + '?' + paramData;
	else
		window.open(actionForm + '?' + paramData);

	return true;
}

function createUploader(){            
    var uploader = new qq.FileUploader({
        element: document.getElementById('btnCargarFiltro'),
        action: 'uploadFiles.php',
        onComplete: function(id, fileName, responseJSON){
        	if(responseJSON.success)
    		{
        		var paramData = 'actionOfForm=cargarFiltro&fileName=' + fileName + '&idCampanna=' + actionPKCampanna;
        		
        		$.ajax({
                    type: 'POST',
                    url: actionForm,
                    data: paramData,
        			dataType: 'json',
                    success: function(jsonObj)
                                        {
                                            if(jsonObj.status === 'OK')
                                            {
                                            	joFilterUbicaciones = eval('(' + jsonObj.joFilterUbicaciones + ')');
                                            	if(!$.isEmptyObject(joFilterUbicaciones)) {
	                                            	joElementosMap = joFilterUbicaciones.joElementosIds;
	                                            	joEVPMap = joFilterUbicaciones.joEVPIds;
	                                            	joProvinciaMap = joFilterUbicaciones.joProvinciaIds;
	                                            	joLocalidadMap = joFilterUbicaciones.joLocalidadIds;
	                                            	joEntidadPoisMap = joFilterUbicaciones.joEntidadPOIs;
	                                            	joFavoritosMap = joFilterUbicaciones.joFavoritosIds;
	                                            	                                            	
	                                            	//Ubicaciones no Visibles
	                                            	joUbicacionesCantidad = eval(jsonObj.joUbicacionesCantidad);
	                                            	joMarkerNotVisibleIds = eval(jsonObj.joMarkerNotVisibleIds);
	                                            	
	                                            	$_actulizarMapa();
	                                            	$_cargarCantidades();
                                            	}
                                            	                                            	
                                            	$_showMessage('OK', 'OK', jsonObj.msg);
                                            }
        									else
        										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                        }
                    });
    		}
        	else
        		$_showMessage('ERR', 'ERROR', responseJSON.error);
        },
    });
}

function $_actulizarMapa()
{	
	if($.isEmptyObject(joFilterUbicaciones.joElementosIds) && $.isEmptyObject(joFilterUbicaciones.joEVPIds) && $.isEmptyObject(joFilterUbicaciones.joProvinciaIds) && $.isEmptyObject(joFilterUbicaciones.joLocalidadIds) && $.isEmptyObject(joFilterUbicaciones.joFavoritosIds)) {
		if(!$.isEmptyObject(joFilterUbicaciones.joEntidadPOIs)) {
			var paramData = 'actionOfForm=actualizarPOIsMapa&joEntidadPOIs=' + encodeURIComponent(JSON.stringify(joFilterUbicaciones.joEntidadPOIs));
			
			$(".loader").show();
			
			$.ajax({
		        type: 'POST',
		        url: actionForm,
		        data: paramData,
				dataType: 'json',
		        success: function(jsonObj)
		                            {
		                                if(jsonObj.status === 'OK')
		                                {
		                                	$.goMap.clearMarkers();
		                                	
		                                	var joDataPolygon = jaDataPolygon[polyConst.POIS];
		                                	
		                                	var latitude = undefined;
		                                	var longitude = undefined;
		                                	$.each(jsonObj.markers, function(i, item) {
		                                		if(latitude == undefined && longitude == undefined) {
		                                			latitude = item.latitude;
		                                			longitude = item.longitude;
		                                		}
		                                		
		                                		if(joDataPolygon.circlePois) {
		                                			$.goMap.createMarker({
			                                			latitude: item.latitude, 
			                                            longitude: item.longitude, 
			                                            html: item.html,
			                                            icon: item.icon,
			                                            draggable: false,
			                                            circlePoly: {radius: joDataPolygon.mtsRadio}
			                                		});
		                                		}
		                                		else {
			                                		$.goMap.createMarker({
			                                			latitude: item.latitude, 
			                                            longitude: item.longitude, 
			                                            html: item.html,
			                                            icon: item.icon,
			                                            draggable: false
			                                		});
		                                		}
		                                	});
		                                	
		                                	$(".loader").hide();
		                                	
		                                	$.goMap.setMap({
		                            			latitude: latitude, 
		                                        longitude: longitude, 
		                                		zoom: 10,
		                                	});
		                                }
		                            }
		        });
		}
		else
			return;
	}
	else {
			
		var paramData = 'actionOfForm=actualizarMapa&tipoFiltro=' + $('#tipoFiltro').val() + '&joFilterUbicaciones=' + encodeURIComponent(JSON.stringify(joFilterUbicaciones));
		
		$(".loader").show();
		
		$.ajax({
	        type: 'POST',
	        url: actionForm,
	        data: paramData,
			dataType: 'json',
	        success: function(jsonObj)
	                            {
	                                if(jsonObj.status === 'OK')
	                                {
	                                	$.goMap.clearMarkers();
	                                	
	                                	var joDataPolygon = jaDataPolygon[polyConst.ELEMENTOS];
	                                	if(!joDataPolygon.circleElementos)
	                                		joDataPolygon = jaDataPolygon[polyConst.EVPS];
	                                	
	                                	joImagenesMapa = jsonObj.imagesMapa;
	                                	var latitude = undefined;
	                                	var longitude = undefined;
	                                	$.each(jsonObj.markers, function(i, item) {
	                                		
	                                		if(joDataPolygon.circleElementos || joDataPolygon.circleEVPs) {
	                                			
	                                			if(item.id.indexOf('P') != -1) {
	                                				
	                                				var visiblePoint = $.goMap.checkInPolygon(item.latitude, item.longitude);
	                                				
			                                		if(!visiblePoint) {
			                                			joMarkerNotVisibleIds.push(item.id);
			                                		}
			                                		else {
			                                			var hasMatch = false;
			                                			for (var index = 0; index < joMarkerNotVisibleIds.length; ++index) {
			                                				var idPoint = joMarkerNotVisibleIds[index];
			                                				if(idPoint == item.id) {
			                                					joMarkerNotVisibleIds.push(item.id);
			                                					hasMatch = true;
			 	                                			   	break;
			                                				}
			                                			}
			                                			
			                                			visiblePoint = !hasMatch;
			                                		}
			                                		
			                                		$.goMap.createMarker({
			                                			id: item.id,
			                                			latitude: item.latitude, 
			                                            longitude: item.longitude, 
			                                            html: item.html,
			                                            icon: item.icon,
			                                            draggable: false,
			                                            visible: visiblePoint
			                                		});
	                                			}
	                                			else {
	                                				if(latitude == undefined && longitude == undefined) {
			                                			latitude = item.latitude;
			                                			longitude = item.longitude;
			                                		}
	                                				
		                                			$.goMap.createMarker({
		                                				id: item.id,
			                                			latitude: item.latitude, 
			                                            longitude: item.longitude, 
			                                            html: item.html,
			                                            icon: item.icon,
			                                            draggable: false,
			                                            circlePoly: {radius: joDataPolygon.mtsRadio}
			                                		});
	                                			}
	                                		}
	                                		else {
		                                		var visiblePoint = $.goMap.checkInPolygon(item.latitude, item.longitude);
		                                		
		                                		if(latitude == undefined && longitude == undefined && visiblePoint) {
		                                			latitude = item.latitude;
		                                			longitude = item.longitude;
		                                		}
		                                		
		                                		if(!visiblePoint) {
		                                			joMarkerNotVisibleIds.push(item.id);
		                                		}
		                                		else {
		                                			var hasMatch = false;
		                                			for (var index = 0; index < joMarkerNotVisibleIds.length; ++index) {
		                                				var idPoint = joMarkerNotVisibleIds[index];
		                                				if(idPoint == item.id) {
		                                					joMarkerNotVisibleIds.push(item.id);
		                                					hasMatch = true;
		 	                                			   	break;
		                                				}
		                                			}
		                                			
		                                			visiblePoint = !hasMatch;
		                                		}
		                                		
		                                		$.goMap.createMarker({
		                                			id: item.id,
		                                			latitude: item.latitude, 
		                                            longitude: item.longitude, 
		                                            html: item.html,
		                                            icon: item.icon,
		                                            draggable: false,
		                                            visible: visiblePoint
		                                		});
	                                		}
	                                	});
	                                	
	                                	$(".loader").hide();
	                                	
	                                	$.goMap.setMap({
	                            			latitude: latitude, 
	                                        longitude: longitude, 
	                                		zoom: 10,
	                                	});
	                                	
	                                	if(joDataPolygon.circleElementos || joDataPolygon.circleEVPs)
	                                		$.goMap.removeEmptyCirclePolygon();
	                                	
	                                	oTableMAP.fnReloadAjax(actionForm + "?actionOfForm=searchMapping");
	                                	bolPrintMarca = false;
	                                }
	                            }
	        });
	}
}

function $_setVisibleMarker(id, bVisible)
{
	for(var i = 0; i < joMarkerNotVisibleIds.length; i++)
	{
		if(joMarkerNotVisibleIds[i] == id)
		{
			joMarkerNotVisibleIds.splice(i,1);
			$.goMap.setVisibleMarkerById(id, bVisible);
			return;
		}
	}
	joMarkerNotVisibleIds.push(id);
	$.goMap.setVisibleMarkerById(id, bVisible);
}


function $_centerMapMarker(lat, lng)
{
	$('#referenceTable').removeClass('hideTable');
	$('#referenceTable').addClass('showTable');
	$('#tablaReferencias').hide("slide", { direction: "left" }, 1000);
	$.goMap.setMap({
		latitude: lat, 
        longitude: lng, 
		zoom: 17,
	});	
}

function $_initGlosarioPop()
{
	$('#btnGlosarioSalir').click( function(e) {
		$('#glosarioDialog').dialog('close');
	});
	
	oTableGlosario = $('#dt_glosario').dataTable( {
							"bJQueryUI": true,
							"sPaginationType": "two_button",
							"bInfo": false,
							"bLengthChange": false,
							"bProcessing": true,
							"sScrollY": "250px",
							"bScrollInfinite": true,
							"bScrollCollapse": false,
							"bPaginate": false,
							"iDisplayLength": -1,
							"bServerSide": true,
							"oLanguage": {
								"sUrl": "js/datatables/js/dataTables.es.txt"
							},
							"sAjaxSource": actionForm + "?actionOfForm=searchGlosario",
							"aoColumns": [
								  			{"sWidth": "7%"},
								  			null,
								  			{"bVisible": false},
								  			{ "sClass": "center", "bSortable": false }
								  		 ]
					});
	
	$('#dt_glosario tbody td img').live('click', function () {
		var nTr = $(this).parents('tr')[0];
		if (oTableGlosario.fnIsOpen(nTr) )
		{
			this.src = "images/details_open.png";
			oTableGlosario.fnClose( nTr );
		}
		else
		{            
			this.src = "images/details_close.png";            
			oTableGlosario.fnOpen( nTr, fnFormatDetailsGlosario(nTr), 'details' );        
		}    
	});
}

function fnFormatDetailsGlosario (nTr)
{
	var aData = oTableGlosario.fnGetData(nTr);
	var sOut = "";
	var paramData =  "actionOfForm=searchGlosarioDetalle&idGlosario=" + aData[0];
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
        async: false,
		dataType: 'html',
        success: function(strHtml)
                            {
        						sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
        						sOut += strHtml;
        						sOut += '</table>';
                            }
    });
		
	return sOut;
}

function $_addMappingFavorito(obj)
{
	var idFav = $(obj).attr('id').replace("fav_", "").replace("grilla_", "");
	var exist = false;
	
	if(!$.isEmptyObject(joFavoritosMap)) {
		$.each(joFavoritosMap, function(i, value) {
			if(value == idFav) {
				joFavoritosMap.splice(i, 1);
				exist = true;
				return false;
			}
		});
	}
	if(!exist) {
		joFavoritosMap.push(idFav);
		$("#fav_"+idFav).attr('src', 'images/fav_activado_tooltip.png');
		$("#fav_grilla_"+idFav).attr('src', 'images/fav_activado_tooltip.png');
	}
	else {
		$("#fav_"+idFav).attr('src', 'images/fav_desactivado_tooltip.png');
		$("#fav_grilla_"+idFav).attr('src', 'images/fav_desactivado_tooltip.png');
	}
	
	joFilterUbicaciones.joFavoritosIds = joFavoritosMap;
}

function $_initPopCampannas()
{
	$('#btnSalirCampannas').click( function(e) {
		$('#mappingCampannaDialog').dialog('close');
	});
	
	var gaiSelected;
	
	oTableCampannas = $('#dt_campannas').dataTable( {
							"bJQueryUI": true,
							"sPaginationType": "two_button",
							"bInfo": false,
							"bLengthChange": false,
							"bAutoWidth": false,
							"bProcessing": true,
							"bServerSide": true,
							"oLanguage": {
								"sUrl": "js/datatables/js/dataTables.es.txt"
							},
							"sAjaxSource": actionForm + "?actionOfForm=searchCampannas",
							"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
								if ( aData[0] == actionPKCampanna ) {
							        $(nRow).addClass('row_selected');
								}
								return nRow;
							},
							"aoColumns": [
							  			null,
							  			null,
							  			{ "sClass": "center", "bSortable": false }
							  		]
						});
	
	$(document).off("click");
	$('#dt_campannas tbody td img').live('click', function () {
		var nTr = $(this).parents('tr')[0];
		if (oTableCampannas.fnIsOpen(nTr) )
		{
			/* This row is already open - close it */
			this.src = "images/details_open.png";
			oTableCampannas.fnClose( nTr );
		}
		else
		{            
			/* Open this row */            
			this.src = "images/details_close.png";            
			oTableCampannas.fnOpen( nTr, fnFormatDetailsCampania(nTr), 'details' );        
		}    
	});
	
	/* Click event handler */
	$('#dt_campannas tbody tr').live('click', function () {
		if(oTableCampannas == undefined)
			return false;

		var aData = oTableCampannas.fnGetData(this);
		if(aData == null)
			return false;
		
		var iId = aData[0];
		actionPKCampanna = aData[0];
		
		gaiSelected =  [];
		if ( $(this).hasClass('row_selected') ) {
            $(this).removeClass('row_selected');
            actionPKCampanna = undefined;
        }
        else {
        	oTableCampannas.$('tr.row_selected').removeClass('row_selected');
            $(this).addClass('row_selected');
            gaiSelected[gaiSelected.length++] = iId;
        }
	});
	
	$('#dt_campannas tbody tr').live('dblclick', function () {
		if(oTableCampannas == undefined)
			return false;
		
		var aData = oTableCampannas.fnGetData(this);
		var iId = aData[0];
		actionPKCampanna = aData[0];
		
		var paramData = 'actionOfForm=cargarFiltroCampanna&idCampanna=' + actionPKCampanna;
		
		$.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK')
                                    {
                                    	$_limpiarFiltrosCampanna();
                                    	
                                    	if(!$.isEmptyObject(jsonObj.joFilterUbicaciones)) { 
	                                    	joFilterUbicaciones = eval('(' + jsonObj.joFilterUbicaciones + ')');
	                                    	joElementosMap = joFilterUbicaciones.joElementosIds;
	                                    	joEVPMap = joFilterUbicaciones.joEVPIds;
	                                    	joProvinciaMap = joFilterUbicaciones.joProvinciaIds;
	                                    	joLocalidadMap = joFilterUbicaciones.joLocalidadIds;
	                                    	joEntidadPoisMap = joFilterUbicaciones.joEntidadPOIs;
	                                    	joFavoritosMap = joFilterUbicaciones.joFavoritosIds;
	                                    	                                            	
	                                    	//Ubicaciones no Visibles
	                                    	joUbicacionesCantidad = eval(jsonObj.joUbicacionesCantidad);
	                                    	joMarkerNotVisibleIds = eval(jsonObj.joMarkerNotVisibleIds);
	                                    	
	                                    	$_actulizarMapa();
	                                    	$_cargarCantidades();
                                    	}
                                    	
                                    	$('#titleCampanna').text(jsonObj.titleCampanna).show();
                                    	
                                    	$_showMessage('OK', 'OK', jsonObj.msg);
                                    }
									else {
										$('#titleCampanna').text(jsonObj.titleCampanna).hide();
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
									}
                                }
        });

        $('#mappingCampannaDialog').dialog('close');
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAgregarCampanna").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEditarCampanna').click( function(e) {
		editProxyShow();
	});
	
	$('#btnEliminarCampanna').click( function(e) {
		delProxyShow();
	});
}

function delArchivoCampanna(idArchivoCampanna, idCampanna)
{
	var paramData = 'actionOfForm=deleteArchivo&idArchivoCampanna=' + idArchivoCampanna + '&idCampanna=' + idCampanna;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK')
										oTableCampannas.fnReloadAjax();
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                }
            });
}

function fnFormatDetailsCampania(nTr)
{
	var aData = oTableCampannas.fnGetData(nTr);
	
	if(aData == null)
		return;
	
	var sOut = "";
	var paramData =  "actionOfForm=searchCampannaDetalle&idCampanna=" + aData[0];
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
        async: false,
		dataType: 'html',
        success: function(strHtml)
                            {
        						sOut = '<table class="tableCampanna">';
        						sOut += strHtml;
        						sOut += '</table>';
                            }
    });
		
	return sOut;
}

function $_initCampannasItemPop()
{
	//Add Click for All Buttons in Pop Form
	$('#btnSalirCampannasItem').click( function(e) {
		$('#campannasItemDialog').dialog('close');
	});
	
	$('#btnGuardarCampannasItem').click( function(e) {
		$('#mapCampannasItemPopForm').submit();
	});
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	//Populate Campanna Data	
	if(action == iConst.EDIT)
	{
		$('#descripcion').val(joDataCampanna.descripcion);
		$('#detalle').val(joDataCampanna.detalle);
	}
	
	$("#campannasItemDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:510, 
		closeOnEscape: false,
		position : ['center',10],		
		dialogClass:'no-close',
		beforeClose: function() { $("#campannasItemDialog").empty(); },
		open: function() {
			$('#campannasItemDialog').css('background','#F5F5F5');
		}
	});
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPKCampanna = undefined;
	action = iConst.NEW;
	oTableCampannas.$('tr.row_selected').removeClass('row_selected');
	$('#campannasItemDialog').load(popCampannasItem).dialog('open');
}

function editProxyShow()
{
	if(actionPKCampanna === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione alg&uacute;n item de la Grilla');
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDIT + "&idCampanna=" + actionPKCampanna;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataCampanna = jsonObj;
        						//Open Pop Dialog
        						$('#campannasItemDialog').load(popCampannasItem).dialog('open');
                            }
        });
	
return true;
}

function delProxyShow()
{
	if(actionPKCampanna === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione alg&uacute;n item de la Grilla');
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteCampannaDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteCampannaDialog').css('background','#F5F5F5');
			$('#btnConfirmDelete').click( function(e) {
				
				var paramData = 'actionOfForm=' + iConst.DELETE + '&idCampanna=' + actionPKCampanna;

			    $.ajax({
			            type: 'POST',
			            url: actionForm,
			            data: paramData,
						dataType: 'json',
			            success: function(jsonObj)
			                                {
			                                    if(jsonObj.status === 'OK'){
													$_showMessage('OK', 'OK', jsonObj.msg);
													
													//Reset State of action and IndexPK
													actionPKCampanna = undefined;
													action = iConst.NEW;
													oTableCampannas.fnReloadAjax();
												}
												else
													$_showMessage('ERR', 'ERROR', jsonObj.msg);
			                                    $('#deleteCampannaDialog').dialog('close');
			                                }
			            });
			});
			$('#btnExitDelete').click( function(e) {
				$('#deleteCampannaDialog').dialog('close');
			})
		}
	});
	$('#deleteCampannaDialog').dialog('open');	
}


function $_saveCampanna(action)
{
	var paramData = 'actionOfForm=addOrEditCampanna&' + $("#mapCampannasItemPopForm").serialize();
	
	if(action == iConst.EDIT)
		paramData += '&idCampanna=' + actionPKCampanna;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#campannasItemDialog').dialog('close');
				oTableCampannas.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}


function $_initPopValidator()
{
	$('#mapCampannasItemPopForm').validate({
		submitHandler: function() {
			$_saveCampanna(action);
		}, 		
		rules: {
			descripcion: {required: true,minlength: 1}
		},
		messages: {
			descripcion: {required: '',minlength: ''}
		}
	});
}

function $_saveFilterCampanna()
{

	if(actionPKCampanna == undefined)
		return false;
	
	var paramData = 'actionOfForm=saveFilterCampanna' + 
					'&joFilterUbicaciones=' + encodeURIComponent(JSON.stringify(joFilterUbicaciones))  + 
					'&joMarkerNotVisibleIds=' +  encodeURIComponent(JSON.stringify(joMarkerNotVisibleIds)) + 
					'&idCampanna=' + actionPKCampanna;
	
	$.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status !== 'OK')
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });	
}

function $_limpiarFiltrosCampanna()
{
	joElementosMap = undefined;
	joEVPMap = undefined;
	joProvinciaMap = undefined;
	joLocalidadMap = undefined;
	joEntidadPoisMap = undefined;
	joFavoritosMap = [];
	joUbicacionesCantidad = [];
	joMarkerNotVisibleIds = [];
	
	var jaDataPolygon = [
	                     	{circlePois: false, mtsRadio: 0},
	                     	{circleElementos: false, mtsRadio: 0},
	                     	{circleEVPs: false, mtsRadio: 0}
	                     ];
	
	joFilterUbicaciones = {
			joElementosIds : undefined, 
			joEVPIds: undefined, 
			joProvinciaIds : undefined, 
			joLocalidadIds: undefined,
			joEntidadPOIs: undefined,
			joFavotirosIds: []
		};
	
	$.goMap.clearMarkers();

	oTableMAP.fnReloadAjax(actionForm + "?actionOfForm=searchMapping&emptyTable=true");
	bolPrintMarca = false;	
}

function $_initPopExcel()
{	
	$('#btnSalirUploadExcel').click( function(e) {
		$('#mappingExcelDialog').dialog('close');
	});
	
	$.ajax({ 
	    url: actionForm, 
	    type:'POST',
	    data: 'actionOfForm=getEVPs', 
	    dataType: 'json', 
	    success: function(json) { 
	    	$('#cmbExcelEVP').append($('<option selected>').text("...").attr('value', ''));
	        $.each(json, function(i, value) {
	        	$('#cmbExcelEVP').append($('<option>').text(value.descripcion).attr('value', value.idEmpresa));
	        });
	    }
	});
	
	$.ajax({ 
	    url: actionForm, 
	    type:'POST',
	    data: 'actionOfForm=getElementos', 
	    dataType: 'json', 
	    success: function(json) { 
	    	$('#cmbExcelElemento').append($('<option selected>').text("...").attr('value', ''));
	        $.each(json, function(i, value) {
	        	$('#cmbExcelElemento').append($('<option>').text(value.descripcion).attr('value', value.idElemento));
	        });
	    }
	});
	
	var uploaderExcel = new qq.FileUploader({
        element: document.getElementById('btnFileUploadExcel'),
        action: 'uploadFiles.php',
        template: '<div class="qq-uploader">' + 
			        '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
			        '<div class="qq-upload-button">Subir XLS</div>' +
			        '<ul class="qq-upload-list"></ul>' + 
			     '</div>',
        onComplete: function(id, fileName, responseJSON){
        	if(responseJSON.success)
    		{
        		var paramData = 'actionOfForm=cargarExcel&fileName=' + fileName;
        		
        		$.ajax({
                    type: 'POST',
                    url: actionForm,
                    data: paramData,
        			dataType: 'json',
                    success: function(jsonObj)
                                        {
                                            if(jsonObj.status === 'OK') {
                                            	joUbicacionesCantidad = jsonObj.joUbicacionesCantidad;
                                            	$_cargarCantidades();
                                            	
                                            	$_showMessage('OK', 'OK', jsonObj.msg);
                                            	$('#mappingExcelDialog').dialog('close');
                                            }
        									else
        										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                        }
                    });
    		}
        	else
        		$_showMessage('ERR', 'ERROR', responseJSON.error);
        }
    });
}

function $_cargarCantidades()
{
	oTableMAP.$('tr').each(function() {
	    var aData = oTableMAP.fnGetData(this);
	    var idFavorito = $(aData[12]).attr('id');
	    var idUbicaion = $('#'+idFavorito).attr('id').split("_")[2];
	    
	    $.each(joUbicacionesCantidad, function(i, item) {
	    	if(item.idUbicacion == idUbicaion) {
	    		$('#cant_'+idUbicaion).text(item.cantidad);
	    		return false;
	    	}
	    });
	});	
}